package com.tanhua.server.service;/*
 *FileName:  VoiceService
 * Author:   ASUS
 * Date  :   2021/5/21 13:55
 * */

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.mongo.Voice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;


@Service
public class VoiceService {

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private UserLikeApi userLikeApi;

    @Reference
    private VoiceApi voiceApi;

    /**
     * 接口名称：桃花传音-发送语音
     *
     * @param soundFile
     * @return
     */
    public ResponseEntity<Object> peachBlossom(MultipartFile soundFile) throws IOException {
        //2. 上传小视频到fastdfs上
        //2.1 获取文件名
        String fileName = soundFile.getOriginalFilename();
        //2.2 获取后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //2.3 上传
        StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), suffix, null);
        //2.4 获取完整的weburl访问地址
        String voiceUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        //获取当前用户id
        Long userId = UserHolder.getUserId();
        Voice voice = new Voice();
        UserInfo userInfo = userInfoApi.findById(userId);
        if (userInfo != null) {
            voice.setId(new ObjectId());
            voice.setUserId(userId);
            voice.setVid(0L);
            voice.setState(0);
            voice.setGender(userInfo.getGender());
            voice.setSoundUrl(voiceUrl);
            voice.setCreated(System.currentTimeMillis());
            voice.setAge(userInfo.getAge());
        }
        voiceApi.saveSound(voice);
        return ResponseEntity.ok(null);
    }

    /**
     * 听语音
     *
     * @return
     */
    public ResponseEntity<Object> listenPeach() {
        //当前登录用户的id
        Long userId = UserHolder.getUserId();
        String key = "Voice_UserId_" + userId;//存储用户接收语音的次数的键
        //从数据库中获取到语音   一次一条
        Voice voice = voiceApi.getVoice(userId);//在查的时候已经排除掉自己的语音
        Long voiceUserId = voice.getUserId();//拿到语音拥有者的id
        UserInfo userInfo = userInfoApi.findById(voiceUserId);
        //然后封装返回的vo
        VoiceVo voiceVo = new VoiceVo();
        voiceVo.setId(voiceUserId.intValue());
        voiceVo.setAvatar(userInfo.getAvatar());
        voiceVo.setNickname(userInfo.getNickname());
        voiceVo.setGender(voice.getGender());
        voiceVo.setAge(userInfo.getAge());
        voiceVo.setSoundUrl(voice.getSoundUrl());
        Integer remainingTimes = (Integer) redisTemplate.opsForValue().get(key);


//        userLikeApi.likeUser(userId,voiceUserId);
//        userLikeApi.notLikeUser(userId,voiceUserId);

        //获取今天剩余的毫秒值
        LocalDateTime midnight = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        long millSeconds = ChronoUnit.MILLIS.between(LocalDateTime.now(), midnight);
        //System.out.println("当天剩余毫秒：" + millSeconds);

        if (remainingTimes != null && remainingTimes > 0 && remainingTimes < 11) {
            remainingTimes--;
            redisTemplate.opsForValue().set(key, remainingTimes, Duration.ofMillis(millSeconds));
            ObjectId id = voice.getId();
            voiceApi.delete(id);
            voiceVo.setRemainingTimes(remainingTimes);
            if (remainingTimes == 0) {//只有这个判断  当次数完了 再发送请求 又重新来了 考虑的是当天这个时效
                return ResponseEntity.status(500).body("剩余次数为0");
            }
//        } else if (remainingTimes == 0) { //这个判断是 当redis中的那个次数为0 的时候  直接返回
//            return ResponseEntity.status(500).body("剩余次数为0");
        } else {//第一次登录为空时
            remainingTimes = 10;
            voiceVo.setRemainingTimes(remainingTimes);
            redisTemplate.opsForValue().set(key, remainingTimes, Duration.ofMillis(millSeconds));
        }
        return ResponseEntity.ok(voiceVo);
    }
}
